import 'dart:math';

extension ListExt<T> on List<T> {
  T? random() {
    if (isEmpty) return null;
    return this[Random().nextInt(length)];
  }

  T? getOrNull(int index) {
    if (index < 0 || index >= length) return null;
    return this[index];
  }

  T? firstOrNull() {
    if (isNotEmpty) return first;
    return null;
  }

  bool all(bool Function(T element) test) {
    for (T element in this) {
      if (!test(element)) return false;
    }
    return true;
  }

  /// 拆分数组
  List<List<T>> splitList(int len) {
    if (len <= 1) {
      return [this];
    }

    List<List<T>> result = [];
    int index = 1;

    while (true) {
      if (index * len < length) {
        List<T> temp = skip((index - 1) * len).take(len).toList();
        result.add(temp);
        index++;
        continue;
      }
      List<T> temp = skip((index - 1) * len).toList();
      result.add(temp);
      break;
    }
    return result;
  }

  Iterable<R> mapIndexed<R>(R Function(int index, T element) convert) sync* {
    var index = 0;
    for (var element in this) {
      yield convert(index++, element);
    }
  }
}

extension NullableListExt<T> on List<T>? {
  bool get isNotNullOrEmpty => this != null && this!.isNotEmpty;
}